
```{r est-in1, include = FALSE}
main_ames <- rio::import("../est/20240429_stayer_analyses_marignal_effects_main.csv")
main_desc <- rio::import("../est/20240429_stayer_analyses_descriptives_main.csv")
main_info <-
  rio::import("../est/20240429_stayer_analyses_model_info_main.csv") %>%
  dplyr::group_by(outcome, predictor, moderator, regional, owner) %>%
  dplyr::arrange(model_id)  %>%
  dplyr::mutate(spec = dplyr::case_when(
    is.na(spec) ~ "All",
    spec == "ltr_since_3 == 0" ~ "Moved last 3", 
    spec == "ltr_since_5 == 0" ~ "Moved last 5", 
    spec == "ltr_since_3 == 1" ~ "Since 3", 
    spec == "ltr_since_5 == 1" ~ "Since 5"
  ))

aux_ames <- rio::import("../est/20240429_stayer_analyses_marignal_effects_aux.csv")
aux_desc <- rio::import("../est/20240429_stayer_analyses_descriptives_aux.csv")
aux_info <-
  rio::import("../est/20240429_stayer_analyses_model_info_aux.csv")
```

## Appendix plots

```{r models-6263-coef}
## Load objects
stayer_coef <-
  rio::import("../est/20240429_stayer_analyses_model_coefficients_aux.csv") %>%
  dplyr::filter(model_id %in% c(3, 14)) %>%
  dplyr::select(-V1) %>%
  dplyr::bind_rows(
    rio::import(
      "../est/20240429_stayer_analyses_model_coefficients_main.csv"
    ) %>%
      dplyr::filter(model_id %in% c(209)) %>%
      dplyr::select(-V1)
  )


## Harmonize variable names
colnames(stayer_coef) <- colnames(stayer_coef) %>%
  gsub("X.", "", .) %>%
  gsub("\\._", "\\_", .) %>%
  gsub(".cold_rent_sqm_cwu_imp1.1", ".1.cold_rent_sqm_cwu_imp1", .) %>%
  gsub(".cold_rent_sqm_cwu_imp2.1", ".1.cold_rent_sqm_cwu_imp2", .) %>%
  gsub(".cold_rent_sqm_cwu_imp3.1", ".1.cold_rent_sqm_cwu_imp3", .) %>%
  gsub(".cold_rent_sqm_cwu_imp4.1", ".1.cold_rent_sqm_cwu_imp4", .) %>%
  gsub(".cold_rent_sqm_cwu_imp5.1", ".1.cold_rent_sqm_cwu_imp5", .) %>%
  gsub(".cold_rent_sqm_umn_imp1.1", ".1.cold_rent_sqm_umn_imp1", .) %>%
  gsub(".cold_rent_sqm_umn_imp2.1", ".1.cold_rent_sqm_umn_imp2", .) %>%
  gsub(".cold_rent_sqm_umn_imp3.1", ".1.cold_rent_sqm_umn_imp3", .) %>%
  gsub(".cold_rent_sqm_umn_imp4.1", ".1.cold_rent_sqm_umn_imp4", .) %>%
  gsub(".cold_rent_sqm_umn_imp5.1", ".1.cold_rent_sqm_umn_imp5", .) %>%
  gsub("gtyp5urban...500k_imp1.1", "gtyp5urban...500k.1_imp1", .) %>%
  gsub("gtyp5urban...500k_imp2.1", "gtyp5urban...500k.1_imp2", .) %>%
  gsub("gtyp5urban...500k_imp3.1", "gtyp5urban...500k.1_imp3", .) %>%
  gsub("gtyp5urban...500k_imp4.1", "gtyp5urban...500k.1_imp4", .) %>%
  gsub("gtyp5urban...500k_imp5.1", "gtyp5urban...500k.1_imp5", .)

## Recode x_names in stayer_coef (to match column names)
stayer_coef <- stayer_coef %>%
  mutate(x_names = x_names %>%
           as.character() %>%
           ifelse(
             startsWith(., "gtyp5urban > 500k"),
             paste0(substr(., 1, nchar("gtyp5urban > 500k")),
                    ".1",
                    substr(., nchar("gtyp5urban > 500k") + 1, nchar(.))),
             .
           )) %>%
  mutate(x_names = x_names %>%
           as.character() %>%
           ifelse(endsWith(., "gtyp5urban > 500k"),
                  paste0(., ".1"),
                  .)) %>%
  mutate(
    x_names = x_names %>%
      gsub("\\(", "", .) %>%
      gsub("\\)", "", .) %>%
      gsub("<", "\\.", .) %>%
      gsub(">", "\\.", .) %>%
      gsub("=", "\\.", .) %>%
      gsub(" ", "\\.", .) %>%
      gsub("\\:", "\\.", .) %>%
      gsub("&", "\\.", .) %>%
      gsub("-", "\\.", .) %>%
      gsub("\\`", "", .)
  )

## Split stayer_coef by model_id, drop empty columns
stayer_coef <- stayer_coef %>%
  group_by(model_id) %>%
  group_split %>%
  lapply(select_if, all_na)

## Stack by imputations
stayer_est <- stayer_coef %>%
  lapply(.,
         function(mod) {
           varying <- mod %>%
             dplyr::select(contains("_imp")) %>%
             names() %>%
             split(
               .,
               mod %>%
                 dplyr::select(contains("_imp")) %>%
                 names() %>%
                 sapply(function(name)
                   substr(name, 1, nchar(name) - 5)) %>%
                 factor(
                   .,
                   levels = mod %>%
                     dplyr::select(contains("_imp")) %>%
                     names() %>%
                     sapply(function(name)
                       substr(name, 1, nchar(name) - 5)) %>%
                     unique()
                 )
             ) %>%
             lapply(function(names)
               sapply(names, function(name)
                 which(names(mod) == name)))
           mod <- mod %>%
             as.data.frame() %>%
             reshape(
               direction = "long",
               varying = varying,
               v.names = names(varying),
               timevar = "imp",
               times = 1:5
             ) %>%
             dplyr::select(-id)
           
           return(mod)
         })

## Split by model_id and imp
stayer_est <- stayer_est %>%
  lapply(.,
         function(mod) {
           mod %>%
             group_by(imp) %>%
             group_split()
         })
```

```{r models-6263-sims}
stayer_imp_sim <- stayer_est %>%
  lapply(.,
         function (mod) {
           b_sim <- lapply(mod,
                           function (imp) {
                             x_names <- imp$x_names
                             b <- as.matrix(imp[, 4])
                             vcov <- as.matrix(imp[, 5:ncol(imp)])
                             vcov <- vcov[, x_names]
                             set.seed(20230329)
                             sim <- MASS::mvrnorm(10000L, b, vcov)
                             
                             return(list(x_names = x_names,
                                         sim = sim))
                           }) 
           x_names <- b_sim[[1]]$x_names
           b_sim <- lapply(b_sim, function (obj)
             obj$sim) %>%
             do.call(rbind, .)
           colnames(b_sim) <- x_names
           
           return(b_sim)
         })
```

### Mediation analysis

#### AfD Support

##### Effect of market rents on the mediator (household rents)

```{r app-treatfx-2-afd, fig.width=8, fig.height=4, out.width="100%"}
ggvote_plot_mfx2(
  ames_data = aux_ames,
  desc_data = aux_desc,
  model_ids = 3,
  add_descriptives = TRUE,
  d = "cmr_arm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)
```


##### Effect of the mediator (household rents)

```{r app-medfx-2-afd, fig.width=8, fig.height=4, out.width="100%"}
ggvote_plot_mfx2(
  ames_data = main_ames,
  desc_data = main_desc,
  model_ids = c(209),
  add_descriptives = TRUE,
  d = "cold_rent_sqm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)
```

##### Effect of the mediator (household rents) by locality

```{r app-medfx-2-afd-loc, fig.width=8, fig.height=4, out.width="100%"}
ggvote_plot_mfx3(
  ames_data = main_ames,
  desc_data = main_desc,
  model_ids = c(254),
  add_descriptives = TRUE,
  d = "cold_rent_sqm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x3 = "gtyp3",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle_left = "Marginal Effect",
  ytitle_right = "",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)
```

##### Total effect of market rents

```{r app-total-2-afd, fig.width=8, fig.height=4, out.width="100%"}
ggvote_plot_mfx2(
  ames_data = main_ames,
  desc_data = main_desc,
  model_ids = 206,
  add_descriptives = TRUE,
  d = "cmr_arm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)
```

##### Controlled direct effect of market rents

```{r app-direct-2-afd, fig.width=8, fig.height=4, out.width="100%"}
ggvote_plot_mfx2(
  ames_data = main_ames,
  desc_data = main_desc,
  model_ids = 209,
  add_descriptives = TRUE,
  d = "cmr_arm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)
```

##### Indirect effect of market rents that unfolds via household rents


```{r app-indirect-2-afd, fig.width=8, fig.height=4, out.width="100%"}
main_aie <- main_ames %>%
  dplyr::filter(model_id == 206) %>%
  dplyr::filter(factor == "cmr_arm_cwu")

mod_vals <-
  aux_ames$log_hinc_eq[aux_ames$model_id == 3 &
                         aux_ames$factor == "cmr_arm_cwu"]

for (n in seq_along(mod_vals)) {
  t_on_m <- stayer_imp_sim[[1]][, "cmr_arm_cwu"] +
    stayer_imp_sim[[1]][, "cmr_arm_cwu.log_hinc_eq"] * mod_vals[n]
  
  m_on_y <- stayer_imp_sim[[3]][, "cold_rent_sqm_cwu"] +
    stayer_imp_sim[[3]][, "log_hinc_eq.cold_rent_sqm_cwu"] * mod_vals[n]
  
  main_aie$AME[n] <- median(t_on_m * m_on_y)
  main_aie$SE[n] <- sd(t_on_m * m_on_y)
  main_aie$lower[n] <- quantile(t_on_m * m_on_y, .025)
  main_aie$upper[n] <- quantile(t_on_m * m_on_y, .975)
}

ggvote_plot_mfx2(
  ames_data = main_aie,
  desc_data = main_desc,
  model_ids = 206,
  add_descriptives = TRUE,
  d = "cmr_arm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)
```

```{r app-mediation-afd, fig.width=12, fig.height=4, out.width="100%"}
p1 <- ggvote_plot_mfx2(
  ames_data = aux_ames,
  desc_data = aux_desc,
  model_ids = 3,
  add_descriptives = TRUE,
  d = "cmr_arm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect of Local\nMarket Rents on HH Rents",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)

p2 <- ggvote_plot_mfx2(
  ames_data = main_ames,
  desc_data = main_desc,
  model_ids = 209,
  add_descriptives = TRUE,
  d = "cold_rent_sqm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect of HH Rents\non AfD Support",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)

p3 <- ggvote_plot_mfx2(
  ames_data = main_aie,
  desc_data = main_desc,
  model_ids = 206,
  add_descriptives = TRUE,
  d = "cmr_arm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Indirect Effect of Local\nMarket Rents on AfD Support",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)

cowplot::plot_grid(p1, p2, p3, ncol = 3L)
```

#### Egotropic worries about the economy

##### Effect of the mediator (household rents)

```{r app-medfx-2-worries, fig.width=4, fig.height=4, out.width="100%"}
ggvote_plot_mfx1(
  ames_data = aux_ames,
  model_ids = 8,
  d = "cold_rent_sqm_cwu",
  x1  = "Homeownership",
  subset_x1 = "Renters",
  ytitle = "Effect of household rents",
  font_size = 15L
)
```

```{r app-medfx-2-worries-by-inc, fig.width=4, fig.height=4, out.width="100%"}
ggvote_plot_mfx2(
  ames_data = aux_ames,
  desc_data = aux_desc,
  model_ids = 14,
  d = "cold_rent_sqm_cwu",
  x1  = "Homeownership",
  subset_x1 = "Renters",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  xtitle = "Log. Equivalized Household Income",
  ytitle = "Effect of household rents",
  font_size = 15L
)
```

##### Indirect effect of market rents that unfolds via household rents


```{r app-indirect-2-worries, fig.width=8, fig.height=4, out.width="100%"}
aux_aie <- aux_ames %>%
  dplyr::filter(model_id == 13) %>%
  dplyr::filter(factor == "cmr_arm_cwu")

mod_vals <-
  aux_ames$log_hinc_eq[aux_ames$model_id == 3 &
                         aux_ames$factor == "cmr_arm_cwu"]

for (n in seq_along(mod_vals)) {
  t_on_m <- stayer_imp_sim[[1]][, "cmr_arm_cwu"] +
    stayer_imp_sim[[1]][, "cmr_arm_cwu.log_hinc_eq"] * mod_vals[n]
  
  m_on_y <- stayer_imp_sim[[2]][, "cold_rent_sqm_cwu"] +
    stayer_imp_sim[[2]][, "log_hinc_eq.cold_rent_sqm_cwu"] * mod_vals[n]
  
  aux_aie$AME[n] <- median(t_on_m * m_on_y)
  aux_aie$SE[n] <- sd(t_on_m * m_on_y)
  aux_aie$lower[n] <- quantile(t_on_m * m_on_y, .025)
  aux_aie$upper[n] <- quantile(t_on_m * m_on_y, .975)
}

ggvote_plot_mfx2(
  ames_data = aux_aie,
  desc_data = aux_desc,
  model_ids = 13,
  add_descriptives = TRUE,
  d = "cmr_arm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)
```


```{r app-mediation-worries, fig.width=12, fig.height=4, out.width="100%"}
p1 <- ggvote_plot_mfx2(
  ames_data = aux_ames,
  desc_data = aux_desc,
  model_ids = 3,
  add_descriptives = TRUE,
  d = "cmr_arm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect of Local\nMarket Rents on HH Rents",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)

p2 <- ggvote_plot_mfx2(
  ames_data = aux_ames,
  desc_data = aux_desc,
  model_ids = 14,
  add_descriptives = TRUE,
  d = "cold_rent_sqm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Marginal Effect of HH Rents\non Economic Worries",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)

p3 <- ggvote_plot_mfx2(
  ames_data = aux_aie,
  desc_data = aux_desc,
  model_ids = 13,
  add_descriptives = TRUE,
  d = "cmr_arm_cwu",
  x1  = "Homeownership",
  x2 = "log_hinc_eq",
  x2_continuous = TRUE,
  subset_x1 = "Renters",
  ytitle = "Indirect Effect of Local\nMarket Rents on Economic Worries",
  xtitle = "Log. Equivalized Household Income",
  font_size = 15L
)

cowplot::plot_grid(p1, p2, p3, ncol = 3L)
```
